package com.tc.dispatch.web.schedule.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.model.GSConstants;
import com.tc.dispatch.gsservice.model.OrderSumMain;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.gsservice.model.ProcessStep;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.model.combinedOrder;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.FloatJsonValueProcessor;
import com.tc.dispatch.gsservice.model.GSConstants;

public class orderJiaGongDetail extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public orderJiaGongDetail() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public float getYield(byte type, String processName, String ssign,
			String spec, int month1, int year1) {

		float ret = 0;
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		/*try {
			ret = gss.getYield(type, processName, ssign + "\\" + spec, month1,
					year1);
		} catch (GSException e) {
			return 1;

		}*/
		return ret;
	}

	public int saveProcess(OrderSumSub oss) {
		System.out.println("after:" + oss.getAfterSpec());
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			// gss.removeProcessStep(oss.getId());
			if(oss.getId().intValue()==0)
				return gss.createOrderSumSub(oss);
			else
			{
				gss.updateOrderSumSub(oss);
				return oss.getId().intValue();
			}
		} catch (GSException e) {

			System.out.println("GSException:" + e.getMessage());
			return 0;

		}

	}

	public boolean updateProcess(OrderSumSub oss) {
		System.out.println("after:" + oss.getAfterSpec());
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			gss.updateOrderSumSub(oss);
			return true;
		} catch (GSException e) {
			System.out.println("updateProcess:" + e.getMessage());
			return false;
		}

	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		

		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();

		OrderSumMain osm = new OrderSumMain();
		OrderSumMain osmDef = new OrderSumMain();
		List processList, processListDef;
		String pos = "0";
		if (sess.getAttribute("position") != null) {
			pos = (String) sess.getAttribute("position");
		}
		;
		if (action.equals("default")) {
			/* 将两个加工列表显示出来 */
			if (Integer.parseInt(pos) == 3)// 表示 刚开始
			{

				try {

					osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
					osmDef = (OrderSumMain) sess
							.getAttribute("OrderSumMainDef");
					sess.setAttribute("position", "4");
				} catch (Exception e) {
					out.print("{success:false, data:'false'}");
				}
			} else {
				osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
				osmDef = (OrderSumMain) sess.getAttribute("OrderSumMainDef");
			}

			JSONObject json = new JSONObject();
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor());
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor());
			cfg.registerJsonValueProcessor(java.lang.Float.class,
					new FloatJsonValueProcessor());

			// BeanUtils.copyProperties();
			json.put("totalProperty", new Integer(1));
			List ret = new ArrayList();
			combinedOrder corder = new combinedOrder();
		//	corder.setOsm(osm.convertToString());
		//	corder.setOsm2(osmDef.convertToString());
			ret.add(corder);
			// ret.addAll(retList);

			JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
			json.put("osmRoot", arr);

			response.getWriter().print(json);
		} else if (action.equals("defaultList")) {
			try {
				// 这里需要先判断一下是否已经有了
				processList = (List) sess.getAttribute("processList");
				OrderSumSub oss = (OrderSumSub) processList.get(0);
				int osmid = oss.getOrderSumId().intValue();
				List testList = gss.findOrderSumSub("where ordersumid=" + osmid
						+ " order by processPos");
				if (testList.size() > 0) {
					processList = testList;
				}
				List retList = new ArrayList();
				Iterator it1;
				it1 = processList.iterator();

				while (it1.hasNext()) {
					retList.add(it1.next());

				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class,
						new FloatJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(retList.size()));
				List ret = new ArrayList();

				// ret.addAll(retList);

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("processRoot", arr);

				response.getWriter().print(json);
			} catch (Exception e) {
				out.print("{success:false, data:'false'}");
			}

		} else if (action.equals("defaultList2")) {
			try {

				processListDef = (List) sess.getAttribute("processListDef");
				OrderSumSub oss = (OrderSumSub) processListDef.get(0);
				int osmid = oss.getOrderSumId().intValue();
				List testList = gss.findOrderSumSub("where ordersumid=" + osmid
						+ " order by processPos");
				if (testList.size() > 0) {
					processListDef = testList;
				}
				List retList = new ArrayList();
				Iterator it2;

				it2 = processListDef.iterator();
				while (it2.hasNext()) {

					retList.add(it2.next());

				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class,
						new FloatJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(retList.size()));
				List ret = new ArrayList();

				// ret.addAll(retList);

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("processRoot", arr);

				response.getWriter().print(json);
			} catch (Exception e) {
				out.print("{success:false, data:'false'}");
			}

		} else if (action.equals("update")) {
			/* specType,scheme */
			osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
			osmDef = (OrderSumMain) sess.getAttribute("OrderSumMainDef");

			String specType = request.getParameter("specType");
			String specType2 = request.getParameter("specType2");
			String scheme = request.getParameter("processScheme");
			String scheme2 = request.getParameter("processScheme2");
			try {
				osm.setSpecType(specType);
				osmDef.setSpecType(specType2);

				osm.setProcessScheme(Integer.valueOf(scheme));
				osmDef.setProcessScheme(Integer.valueOf(scheme));

				// gss.createOrderSumMain(osm);
				// gss.createOrderSumMain(osmDef);

				sess.removeAttribute("OrderSumMain");
				sess.setAttribute("OrderSumMain", osm);

				sess.removeAttribute("OrderSumMainDef");
				sess.setAttribute("OrderSumMainDef", osmDef);
				/* 下面需要建立子表的加工列表，根据加工计算加工面积，加工费啥的还没有算 */
				processList = new ArrayList();

				List sortList = gss.findProcessStep(" where specName='"
						+ specType + "' and scheme=" + scheme);
				Iterator it = sortList.iterator();
				ProcessStep ps;
				while (it.hasNext()) {
					ps = (ProcessStep) sortList;
					OrderSumSub oss = new OrderSumSub();
					oss.setProcessName(ps.getProcessName());
					oss.setProcessPos(new Integer(ps.getProcessPos()));
					oss.setType((byte) 0);
					processList.add(oss);
				}

				processListDef = new ArrayList();

				it = sortList.iterator();
				while (it.hasNext()) {
					ps = (ProcessStep) sortList;
					OrderSumSub oss = new OrderSumSub();
					oss.setProcessName(ps.getProcessName());
					oss.setProcessPos(new Integer(ps.getProcessPos()));
					oss.setType((byte) 1);
					processListDef.add(oss);
				}

				sess.setAttribute("processList", processList);
				sess.setAttribute("processListDef", processListDef);

				// response.sendRedirect("order/orderProcessIndex.jsp");
			} catch (Exception e) {
				out.print("{success:false, data:'false'}");
			}
			out.print("{success:true, data:'sucess'}");

		} else if (action.equals("sort")) {
			try {
				List sortList = gss.findProcessStep("");
				Iterator it = sortList.iterator();
				ProcessStep ps;
				List ret = new ArrayList();
				List retList = new ArrayList();

				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					if (ret.indexOf(ps.getSpecName()) < 0) {
						ret.add(ps.getSpecName());
						retList.add(ps);
					} else {
						// sortList.remove(ps);
					}
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}

		} else if (action.equals("scheme")) {
			try {
				String sort = request.getParameter("sortType");
				List sortList = gss.findProcessStep(" where specName='" + sort
						+ "'");
				Iterator it = sortList.iterator();
				ProcessStep ps;
				List ret = new ArrayList();
				List retList = new ArrayList();
				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					if (ret.indexOf(new Integer(ps.getScheme())) < 0) {
						ret.add(new Integer(ps.getScheme()));
						retList.add(ps);
					}
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				// json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("root", arr);
				// json.

				response.getWriter().print(json);
			} catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}
		} else if (action.equals("step")) {
			try {
				String sort = request.getParameter("sortType");
				String scheme = request.getParameter("scheme");
				List sortList = gss.findProcessStep(" where specName='" + sort
						+ "' and scheme=" + scheme);
				List ret = sortList;
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (GSException e) {
				out.print("{success:false, data:'false'}");
			}
		}

		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
